package model

import (
	"RestaurantApp/utils"
	"github.com/go-redis/redis"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/wonderivan/logger"
	"time"
)

var DB *gorm.DB

func GetOrmEngine(cfg *utils.DatabaseConfig) {
	database := cfg.DbName
	username := cfg.User
	password := cfg.Password
	host := cfg.Host
	port := cfg.Port
	connStr := username + ":" + password + "@(" + host + ":" + port + ")/" + database + "?charset=utf8&parseTime=true"
	//connStr := "root:Qq761090@(122.9.162.21:3306)/cloudrestaurant?charset=utf8&parseTime=true"
	db, err := gorm.Open("mysql", connStr)
	if err != nil {
		logger.Error(err.Error())
	}
	db.SingularTable(true)       //默认不加复数s
	db.DB().SetMaxIdleConns(20)  //设置连接池，空闲
	db.DB().SetMaxOpenConns(100) //设置打开最大连接
	db.DB().SetConnMaxLifetime(time.Second * 30)
	db.AutoMigrate(&FoodCategory{}, &Goods{}, &Shop{}, &Member{})
	logger.Info("数据库自动迁移完成")
	DB = db
}

var RedisClient *redis.Client

func GetRedisClient(config *utils.RedisConfig) {
	client := redis.NewClient(&redis.Options{
		Addr:     config.Addr + ":" + config.Port,
		Password: config.Password,
		DB:       config.Db,
	})
	RedisClient = client
	logger.Info("redis client初始化完成")

}
